# *-*- coding:utf-8 -*-
# @Author  : Eliza
# @Time    : 2021/7/18 23:21
# @Software : RubyMine

#Thread < 0bject
# Thread.new { do_some_thing }

def foo
  10.times { puts "Call foo at #{Time.now}" }
  sleep(0.5)
end

def bar
  10.times { puts "Call bar at #{Time.now}" }
  sleep(0.5)
end

p '*' * 10 + 'start' + '*' * 10
t1 = Thread.new { foo() }
t2 = Thread.new { bar() }
t1.join
t2.join
p '*' * 10 + 'end' + '*' * 10

###Thread . current hash
count = 0
arr = []
10.times do |i|
  arr[i] = Thread.new {
    sleep(rand(0) / 10.0)
    Thread.current["count"] = count
    count += 1 }
end
arr.each { |t| t.join; print t["count"], "," }
puts "count = #{count}"

puts "---Thread priority--"
count1 = count2 = 0
a = Thread.new do
  loop { count1 += 1 }
end
a.priority = -1 #会给 它分配更多的时间，优先级

b = Thread.new do
  loop { count2 += 1 }
end
b.priority = -2
sleep 1
puts count1
# 17754996
# 4780222
puts count2

puts "-----Thread exception------"
Thread.abort_on_exception = true
t1 = Thread.new do
  puts "In new thread"
  raise "Exception from thread"
end
sleep(1)
# t1.join
puts "not reached"
# https://www.bilibili.com/video/BV1RJ411Y7A4?p=19